//
//  SINAStudentMainViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2017/12/20.
//  Copyright © 2017年  androidlongs. All rights reserved.
//

#import "SINAStudentMainViewController.h"
#import "SINAControllerUtils.h"
#import "SMSwipeView.h"
#import "SINAHomeDateItemCollectionViewCell.h"
#import "SINAStuDateItemFlowLayout.h"
#import "SINACircularBeadUtils.h"
#import "SINACalendarUtils.h"
#import "SINAUiviewClickLiserner.h"
#import "SINADateModel.h"
#import "SINAStuHomeCoursItemModel.h"
#import "SINAStueHomeCourseItemTableViewCell.h"
#import "SINAStueHomeActivityItemTableViewCell.h"
#import "SINAUserModel.h"
#import "SINAStuActivityAddItemViewController.h"
#import "SINASINAStuHomeCoursItemModel2.h"
#import "SINAStuActivityDesViewController.h"
#import "SINAStuActivityLeaveWordViewController.h"
#import "SINAStuActivityTargetModel.h"
#import "SINAStuActivityImpressModel.h"
#import "SINAMsgItemModel.h"
#import "SINAHeaderMsgItemTableViewCell.h"
#import "FMDB.h"
#import "SINAUIDevice.h"
#import "JPUSHService.h"
#import "SINAAskListPageViewController.h"
#import "SINAMainMsgViewController.h"
#import "SINAPickDateView.h"
#import "SINACommonTimePickView.h"
#import "XLCardSwitch.h"
#import "SINAMsgDetaileViewController.h"

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>



static NSString * identifier = @"SINAHomeDateItemTableViewCell";

@interface SINAStudentMainViewController ()<SMSwipeDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDelegate,UITableViewDataSource,CommonTimeSelectViewDelegate,XLCardSwitchDelegate,AMapLocationManagerDelegate,AMapSearchDelegate>

@property (weak, nonatomic) IBOutlet UIView *mainContentView;


@property(assign,nonatomic) BOOL isFirstLoading;
@property (strong, nonatomic) UILabel *noCourseStateLabel;


@property(nonatomic) UIRefreshControl *refreshControl;

@property (strong, nonatomic)  UILabel *noDataUiLabel;

@property (nonatomic, strong) FMDatabase *db;

@property(strong,nonatomic) SMSwipeView *swipeView;

@property (nonatomic, strong) UICollectionView * collectionView;

@property (nonatomic,assign) NSInteger dateItemWidth;

@property (nonatomic,strong) UIView * headerDateItemUIview;
@property (nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *dateArray;
@property(nonatomic,strong) NSMutableArray *courseItemArray;
//首页消息列表
@property(nonatomic,strong) NSMutableArray *headeMsgArray;

@property(nonatomic,strong) NSString *locationLat;
@property(nonatomic,strong) NSString *locationLng;

@property(nonatomic,strong) UILabel *headerLabel;

@property(nonatomic,strong) UILabel *currentTimeLabel;
@property(nonatomic,strong) UILabel *currentDayLabel;

@property(nonatomic,assign) NSInteger currentYear;
@property(nonatomic,assign) NSInteger currentMonth;
@property(nonatomic,assign) NSInteger currentDay;
@property(nonatomic,assign) NSInteger currentPos;
@property(nonatomic,strong) NSString *currentWeek;

@property(nonatomic,strong) AMapLocationManager *locationManager;


@property(nonatomic,strong) NSString *currentSelectTime;

@property(nonatomic,strong) NSString  *preUpdateLocationTime;


@property(nonatomic,strong)  XLCardSwitch *msgCardSwitch;

@property(nonatomic,assign) NSInteger oldY;
@property(nonatomic,assign) BOOL isMoveIcon;

@property(nonatomic,strong) UIView *addActivityUIView;
@property(nonatomic,strong) UIImageView *addActivityImageView;

@property(nonatomic,strong) AMapSearchAPI *search;



@end


@implementation SINAStudentMainViewController

-(void)viewWillAppear:(BOOL)animated{
    //    self.navigationController.navigationBar.hidden=YES;
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    self.navigationController.hidesBottomBarWhenPushed=NO;
    //加载消息
    [self loadingHeaderMsgFunction];
    
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
}
- (void)InfoNotificationAction:(NSNotification *)notification{
    DLog(@"课程刷新通知 %@",notification.userInfo);
    [self loadingCourseFunction:self.currentSelectTime];
    
}
- (void)jpushNotificationFunction:(NSNotification *)dic{
    
    DLog(@"极光推送通知------%@",dic.userInfo[@"pushMsgType"]);
    
    NSString *pushMsgType = dic.userInfo[@"pushMsgType"];
    
    if (pushMsgType!=nil&& [pushMsgType isEqualToString:@"TECALERTCOURSETIME"]){
        //调课
        //刷新当前页面数据
        [self loadingCourseFunction:self.currentSelectTime];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else if (pushMsgType!=nil&& [pushMsgType isEqualToString:@"TECCOURSESIGN"]){
        DLog(@"点名签到 通知");
        //点名签到
        [self.navigationController popToRootViewControllerAnimated:YES];
        //刷新当前页面数据
        [self loadingCourseFunction:self.currentSelectTime];
        //显示签到提示
        NSString *syllabusuuid = dic.userInfo[@"syllabusuuid"];
        NSString *syllabusacuuid = dic.userInfo[@"syllabusacuuid"];
        NSString *msgContent= dic.userInfo[@"msgContent"];
        NSString *signstarttime=dic.userInfo[@"signstarttime"];
        
        NSString *lat= dic.userInfo[@"lat"];
        NSString *lon= dic.userInfo[@"lon"];
        
        DLog(@"课程签到 ： %@ %@",lat,lon);
        [self showSignPopWindow:syllabusuuid andWithCourseUid:syllabusacuuid andWithMsgContent:msgContent andWithLat:lat andWithLon:lon andWithSignTime:signstarttime];
    }else if(pushMsgType!=nil&& [pushMsgType isEqualToString:@"STUFORMTEAM"]){
        //STUFORMTEAM 组队
        self.isFirstLoading=NO;
        [self loadingHeaderMsgFunction];
    }
    
}

-(void) showSignPopWindow:(NSString *)syllabusuuid andWithCourseUid:(NSString*)syllabusacuuid andWithMsgContent:(NSString*)msgContent andWithLat:(NSString*)lat andWithLon:(NSString*)lon andWithSignTime:(NSString*)signStartTime{
    
    if (msgContent==nil) {
        [self loadingCourseFunction:self.currentSelectTime];
        return;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"签到提示" message:msgContent preferredStyle:UIAlertControllerStyleAlert];
    // 确定
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"签到" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
        // [dict setObject:model.courseUid forKey:@"syllabusacuuid"];
        SINAStuHomeCoursItemModel* model = [[SINAStuHomeCoursItemModel alloc]init];
        model.courseId = syllabusacuuid;
        model.courseSyId = syllabusuuid;
        model.courseLocationLat = lat;
        model.courseLocationLon =lon;
        model.tecSignStartTime=signStartTime;
        
        if ([self checkCoureSignFunction:model]) {
            [self coureSignFunction:model:1];
        }
    }];
    
    [alert addAction:okAction];
    [self presentViewController:alert animated:true completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"首页";
    self.navigationController.navigationBar.barStyle = UIStatusBarStyleLightContent;
    
    [self initMapFunction];
    
    [self initLocationFunction];
    
    [self initTimeFunction:0];
    [self initView];
    
    [self initJpushFunction];
    [self initDatasFunction];
    [self loadRefreshView];
    
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.swipeView andWithBlick:^(UIView *view) {
        SINAMainMsgViewController
        *settingController = [[SINAMainMsgViewController alloc]initWithNibName:@"SINAMainMsgViewController" bundle:nil];
        settingController.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:settingController animated:YES];
    }];
}
-(void) initLocationFunction{
    self.isFirstLoading = NO;
    self.dateItemWidth = (mainW-24*2)/5;
    self.headeMsgArray= [[NSMutableArray alloc]init];
    
    /*
     本地消息缓存 加载处理
     */
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"sjschool.sqlite"];
    
    FMDatabase *db = [FMDatabase databaseWithPath:filename];
    self.db = db;
}

-(void) initMapFunction{
    [AMapServices sharedServices].apiKey =mapKey;
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //   定位超时时间，最低2s，此处设置为10s
    self.locationManager.locationTimeout =10;
    //   逆地理请求超时时间，最低2s，此处设置为10s
    self.locationManager.reGeocodeTimeout = 10;
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    
    //OnlineLocation* indoorLocation = [[OnlineLocation alloc]initWithDelegate:self];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;

    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
       
        if (error)
        {
            DLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            self.preUpdateLocationTime=nil;
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        DLog(@"location:%@", location);
        
        if (regeocode)
        {
            DLog(@"reGeocode:%@", regeocode);
            self.preUpdateLocationTime=[SINACalendarUtils currentTimeStr];
            
            self.locationLat=[NSString stringWithFormat:@"%f",location.coordinate.latitude];
            self.locationLng=[NSString stringWithFormat:@"%f",location.coordinate.longitude];
            
            AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
            
            request.location            = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
            //request.keywords            = @"电影院";
            /* 按照距离排序. */
            request.sortrule            = 0;
            request.requireExtension    = YES;
            [self.search AMapPOIAroundSearch:request];
        }
    }];
    
}
/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    
    //B0FFIL6V07
    //万科中心A5写字楼
    //解析response获取POI信息，具体解析见 Demo
    
    
}
-(void) initJpushFunction{
    //推送注册本地通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jpushNotificationFunction:)name:notificationKeyNameStuHome object:nil];
    // 1.注册通知 添加了新的寻找达人 刷新列表
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationAction:) name:@"stuActivityAddFindOther" object:nil];
}
-(void) initDatasFunction{
    
    
    NSString *currentTime = [SINACalendarUtils currentTimeStr];
    DLog(@"currentTime is %@ ",currentTime);
    
    //课程信息
    for (NSInteger i=0; i<5; i++) {
        SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
        coursItemModel.courseTitle=@"思想政治与修养";
        coursItemModel.courseTime=@"8:00-10:00";
        coursItemModel.courseLocation=@"文学楼303";
        coursItemModel.itemTime=@"8:00";
        coursItemModel.itemType=@"1";
        coursItemModel.courseaStatue=[NSString stringWithFormat:@"%ld",i%4];
        
        coursItemModel.itemTime=[NSString stringWithFormat:@"%lf",[currentTime doubleValue]+i*8000];
        [self.courseItemArray addObject:coursItemModel];
    }
    //组队信息 未组队成功 未显示详情
    //组队 未组队成功 点击显示
    for (NSInteger i=0; i<10; i++) {
        SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
        coursItemModel.courseTitle=@"";
        
        coursItemModel.courseTime=@"8:00-10:00";
        coursItemModel.courseLocation=@"文学楼303";
        coursItemModel.itemTime=@"8:00";
        coursItemModel.activityStatue=@"1";
        coursItemModel.activityShowDetaile=NO;
        coursItemModel.itemType=@"2";
        coursItemModel.activityStartTime=[NSString stringWithFormat:@"%ld",(long)i];
        coursItemModel.activityStopTime=[NSString stringWithFormat:@"%ld",(long)i];
        
        coursItemModel.courseaStatue=[NSString stringWithFormat:@"%ld",i%4];
        coursItemModel.itemTime=[NSString stringWithFormat:@"%lf",[currentTime doubleValue]+i*1000+10*1000];
        //想与你组队的人
        NSMutableArray *arry1=[[NSMutableArray alloc]init];
        for (NSInteger j=0; j<=10; j++) {
            //            NSDictionary  *dic = [NSDictionary dictionaryWithObject:@"http://pic106.nipic.com/file/20160808/22731693_125633959000_2.jpg" forKey:@"userTitleImage"];
            SINASINAStuHomeCoursItemModel2 *userModel = [[SINASINAStuHomeCoursItemModel2 alloc]init];
            userModel.userTitleImageUrl=@"http://pic106.nipic.com/file/20160808/22731693_125633959000_2.jpg";
            userModel.activityStartTime=[NSString stringWithFormat:@"%ld",(long)j];
            userModel.activityStopTime=[NSString stringWithFormat:@"%ld",(long)j];
            [arry1 addObject:userModel];
        }
        coursItemModel.teamUserList = arry1;
        //发起组队的人
        NSMutableArray *arry2=[[NSMutableArray alloc]init];
        for (NSInteger j=0; j<=20; j++) {
            SINASINAStuHomeCoursItemModel2 *userModel = [[SINASINAStuHomeCoursItemModel2 alloc]init];
            userModel.userTitleImageUrl=@"http://pic106.nipic.com/file/20160808/22731693_125633959000_2.jpg";
            userModel.activityStartTime=[NSString stringWithFormat:@"%ld",(long)j];
            userModel.activityStopTime=[NSString stringWithFormat:@"%ld",(long)j];
            [arry2 addObject:userModel];
        }
        coursItemModel.otherUserList = arry2;
        
        [self.courseItemArray addObject:coursItemModel];
    }
    
    //组队信息 组队成功
    for (NSInteger i=0; i<25; i++) {
        SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
        coursItemModel.courseTitle=@"";
        coursItemModel.activityShowDetaile=NO;
        coursItemModel.activityStatue=@"2";
        coursItemModel.courseTime=@"8:00-10:00";
        coursItemModel.courseLocation=@"文学楼303";
        coursItemModel.itemTime=@"8:00";
        coursItemModel.itemType=@"2";
        coursItemModel.courseaStatue=[NSString stringWithFormat:@"%ld",i%4];
        coursItemModel.itemTime=[NSString stringWithFormat:@"%lf",[currentTime doubleValue]+i*10*60*1000+40*60*1000];
        if (i%3==0) {
            coursItemModel.itemType=@"2";
            coursItemModel.activityStatue=@"4";
        }
        //小目标  SINAStuActivityTargetModel
        NSMutableArray *targetArray = [[NSMutableArray alloc]init];
        for (NSInteger i=0; i<3; i++) {
            SINAStuActivityTargetModel *targetModel = [[SINAStuActivityTargetModel alloc]init];
            targetModel.title = [NSString stringWithFormat:@"小目标%ld",(long)i];
            if (i!=0) {
                targetModel.startTime=[[SINACalendarUtils currentTimeStr] integerValue];
            }
            [targetArray addObject:targetModel];
        }
        
        //随笔 SINAStuActivityImpressModel.h
        
        NSMutableArray *impressArray = [[NSMutableArray alloc]init];
        for (NSInteger i=0; i<5; i++) {
            SINAStuActivityImpressModel *targetModel = [[SINAStuActivityImpressModel alloc]init];
            targetModel.impressTime=@"2018年01月22日 10:45";
            NSMutableArray *imageArray1 = [[NSMutableArray alloc]init];
            for (NSInteger j=0; j<3; j++) {
                [imageArray1 addObject:@"http://img.tupianzj.com/uploads/allimg/160809/9-160P9223542.jpg"];
            }
            targetModel.temaImageArray=imageArray1;
            switch (i) {
                case 0:{
                    targetModel.impressDes=@"很好";
                    //内容图片
                    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
                    for (NSInteger j=0; j<3; j++) {
                        [imageArray addObject:@"http://img.tupianzj.com/uploads/allimg/160809/9-160P9223542.jpg"];
                    }
                    targetModel.temaImageArray=imageArray;
                }
                    break;
                case 1:
                    targetModel.impressDes=@"很好很好很好很好很好很好很好";
                    break;
                case 2:
                    targetModel.impressDes=@"很好很好很好很好很好很好很好很好很好很好很好很好很好";
                    break;
                    
                case 3:{
                    //内容图片
                    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
                    for (NSInteger j=0; j<7; j++) {
                        [imageArray addObject:@"http://img.tupianzj.com/uploads/allimg/160809/9-160P9223542.jpg"];
                    }
                    targetModel.temaImageArray=imageArray;
                    
                    targetModel.impressDes=@"很好很好很好很好很好很好很好很好很好很好很好很好很好很好很好很好很好很好";
                }
                    
                    break;
                case 4:{
                    //内容图片
                    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
                    for (NSInteger j=0; j<6; j++) {
                        [imageArray addObject:@"http://img.tupianzj.com/uploads/allimg/160809/9-160P9223542.jpg"];
                    }
                    targetModel.temaImageArray=imageArray;
                    
                    
                    targetModel.impressDes=@"很好很好很好很好很好很好";
                }
                    break;
                default:
                    targetModel.impressDes=@"很好很好很好很好很好很好很好很好很好很好很好";
                    break;
            }
            [impressArray addObject:targetModel];
        }
        coursItemModel.teamImpressionArray=impressArray;
        coursItemModel.teamTargetArray = targetArray;
        [self.courseItemArray addObject:coursItemModel];
    }
    
    //组队信息 组队成功 组队事务完成 显示简介
    for (NSInteger i=0; i<5; i++) {
        SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
        coursItemModel.courseTitle=@"";
        coursItemModel.activityShowDetaile=NO;
        coursItemModel.activityStatue=@"3";
        coursItemModel.courseTime=@"8:00-10:00";
        coursItemModel.courseLocation=@"文学楼303";
        coursItemModel.itemTime=@"8:00";
        coursItemModel.itemType=@"2";
        coursItemModel.courseaStatue=[NSString stringWithFormat:@"%ld",i%4];
        coursItemModel.itemTime=[NSString stringWithFormat:@"%lf",[currentTime doubleValue]+i*30*60*1000+40*60*1000];
        
        //小目标  SINAStuActivityTargetModel
        NSMutableArray *targetArray = [[NSMutableArray alloc]init];
        for (NSInteger i=0; i<3; i++) {
            SINAStuActivityTargetModel *targetModel = [[SINAStuActivityTargetModel alloc]init];
            targetModel.title = [NSString stringWithFormat:@"小目标%ld",(long)i];
            [targetArray addObject:targetModel];
        }
        
        coursItemModel.teamTargetArray = targetArray;
        
        [self.courseItemArray addObject:coursItemModel];
    }
    //组队信息 组队成功 组队事务完成 显示详情
    for (NSInteger i=0; i<5; i++) {
        SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
        coursItemModel.courseTitle=@"";
        coursItemModel.activityShowDetaile=NO;
        coursItemModel.activityStatue=@"3";
        coursItemModel.courseTime=@"8:00-10:00";
        coursItemModel.courseLocation=@"文学楼303";
        coursItemModel.itemTime=@"8:00";
        coursItemModel.itemType=@"2";
        coursItemModel.courseaStatue=[NSString stringWithFormat:@"%ld",i%4];
        coursItemModel.itemTime=[NSString stringWithFormat:@"%lf",[currentTime doubleValue]+i*60*60*1000+40*60*1000];
        //内容图片
        NSMutableArray *imageArray = [[NSMutableArray alloc]init];
        for (NSInteger j=0; j<i; j++) {
            [imageArray addObject:@"http://img.tupianzj.com/uploads/allimg/160809/9-160P9223542.jpg"];
        }
        
        switch (i) {
            case 0:
                coursItemModel.activityDes=@"很好";
                break;
            case 1:
                coursItemModel.activityDes=@"很好很好很好很好很好很好很好";
                break;
            case 2:
                coursItemModel.activityDes=@"很好很好很好很好很好";
                break;
                
            case 3:
                coursItemModel.activityDes=@"很好很好很好很好很好";
                break;
            case 4:
                coursItemModel.activityDes=@"很好很好很好很好很好很好很好很好很好很好";
                break;
            default:
                coursItemModel.activityDes=@"很好很好很好很好很好很好很好很好很好很好很好很好";
                break;
        }
        
        coursItemModel.temaImageArray = imageArray;
        [self.courseItemArray addObject:coursItemModel];
    }
    [self.courseItemArray removeAllObjects];
    [self.collectionView reloadData];
    [self.tableView reloadData];
    
}
//加载首页最新消息
-(void) loadingHeaderMsgFunction{
    
    //[self startLoading];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@?receiveruuid=%@",baseUrl,userMsgListUrl,[[SINACommonUserHelper share] getUserModel].userUid] success:^(id responseData) {
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *result = responseData[@"content"];
            if (result!=nil&&result.count>0) {
                [self.headeMsgArray removeAllObjects];
                for (NSInteger i=0; i<result.count; i++) {
                    NSDictionary *dic = result[i];
                    SINAMsgItemModel *model = [[SINAMsgItemModel alloc]initWithDict:dic];
                    
                    XLCardItem *item = [[XLCardItem alloc]init];
                    item.msgItemModel = model;
                    
                    [self.headeMsgArray addObject:item];
                }
                
                if (0==0) {
                    self.msgCardSwitch.items=self.headeMsgArray;
                    [weakSelf loadingCourseFunction:self.currentSelectTime];
                    return ;
                }
                // 3.打开数据库
                if ([weakSelf.db open]) {
                    //[self.db executeUpdate:@"DROP TABLE IF EXISTS t_stu_msg;"];
                    // 4.创表
                    BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_stu_msg (id integer PRIMARY KEY AUTOINCREMENT,  msgid integer,createtime text,messagetype text,messagetypename text,msgtitle text,createuser integer,msgcontent text,msgread integer);"];
                    if (result) {
                        DLog(@"成功创表");
                        for (NSInteger i=0; i<self.headeMsgArray.count; i++) {
                            SINAMsgItemModel *model = self.headeMsgArray[i];
                            FMResultSet *resultSet = [self.db executeQuery:[NSString stringWithFormat:@"SELECT * FROM t_stu_msg where msgid=%@",model.msgId]];
                            BOOL isTo=NO;
                            // 2.遍历结果
                            while ([resultSet next]) {
                                isTo = YES;
                            }
                            if (!isTo) {
                                //插入
                                BOOL res= [self.db executeUpdate:@"INSERT INTO t_stu_msg (msgid, createtime,messagetype,messagetypename,msgtitle,createuser,msgcontent,msgread) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[NSString stringWithFormat:@"%@",model.msgId ],model.time,[NSString stringWithFormat:@"%@",model.msgType],model.msgTypeName,model.msgTitle,[NSString stringWithFormat:@"%@",model.msgCreateUserId ],model.msgContent,[NSString stringWithFormat:@"%d",1]];
                                
                                if (!res) {
                                    DLog(@"error when insert db table");
                                } else {
                                    DLog(@"success to insert db table");
                                }
                            }
                            
                        }
                        
                        [self.headeMsgArray removeAllObjects];
                        //1 未读 2 已读
                        FMResultSet *resultSet = [self.db executeQuery:[NSString stringWithFormat:@"SELECT * FROM t_stu_msg where msgread=1  order by id desc"]];
                        while ([resultSet next]) {
                            NSString * ID = [resultSet stringForColumn:@"msgid"];
                            NSString *createtime = [resultSet stringForColumn:@"createtime"];
                            NSString *messagetype = [resultSet stringForColumn:@"messagetype"];
                            NSString *messagetypename = [resultSet stringForColumn:@"messagetypename"];
                            NSString *title = [resultSet stringForColumn:@"msgtitle"];
                            NSString *createuser = [resultSet stringForColumn:@"createuser"];
                            NSString *content = [resultSet stringForColumn:@"msgcontent"];
                            //                            NSString *read = [resultSet stringForColumn:@"msgread"];
                            SINAMsgItemModel *model = [[SINAMsgItemModel alloc]init];
                            model.msgId = ID;
                            model.time = createtime;
                            model.msgType = messagetype;
                            model.msgTypeName = messagetypename;
                            model.msgTitle = title;
                            model.msgCreateUserId =createuser;
                            model.msgContent = content;
                            
                            XLCardItem *item = [[XLCardItem alloc]init];
                            item.msgItemModel = model;
                            
                            [self.headeMsgArray addObject:item];
                            
                            
                        }
                        if (self.headeMsgArray.count>0) {
                            
                            
                            self.msgCardSwitch.items=self.headeMsgArray;
                            
                            
                            if (weakSelf.tableView.frame.origin.y!=CGRectGetMaxY(weakSelf.msgCardSwitch.frame)+5) {
                                
                                [UIView animateWithDuration:0.2 animations:^{
                                    weakSelf.tableView.frame=CGRectMake(0, CGRectGetMaxY(weakSelf.msgCardSwitch.frame)+5, mainW, mainH-CGRectGetMaxY(weakSelf.msgCardSwitch.frame)-58);
                                }];
                            }
                            
                        }else{
                            
                            self.msgCardSwitch.items=nil;
                            if (weakSelf.tableView.frame.origin.y!=self.msgCardSwitch.frame.origin.y) {
                                
                                [UIView animateWithDuration:1 animations:^{
                                    weakSelf.tableView.frame=CGRectMake(0,self.msgCardSwitch.frame.origin.y, mainW, mainH-self.msgCardSwitch.frame.origin.y-58);
                                }];
                                [UIView animateWithDuration:1 animations:^{
                                    weakSelf.tableView.frame=CGRectMake(0,self.msgCardSwitch.frame.origin.y, mainW, mainH-self.msgCardSwitch.frame.origin.y-58);
                                } completion:^(BOOL finished) {
                                    [YPXToastView showToastViewWithText:@"暂无最新消息" andDuration:1 andParentView:weakSelf.tableView];
                                }];
                            }
                        }
                        
                    } else {
                        DLog(@"创表失败");
                    }
                }
                
                
                
                
            }else{
                //加载消息失败 隐藏消息列表
                DLog(@"加载消息失败 隐藏消息列表");
                
            }
            
        }else{
            //加载消息失败 隐藏消息列表
            DLog(@"加载消息失败 隐藏消息列表");
        }
        if (!weakSelf.isFirstLoading) {
            weakSelf.isFirstLoading=YES;
            [weakSelf loadingCourseFunction:[SINACalendarUtils currentTimeStr]];
        }else{
            if(self.courseItemArray.count==0){
                [weakSelf loadingCourseFunction:[SINACalendarUtils currentTimeStr]];
            }
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        //加载消息失败 隐藏消息列表
        DLog(@"加载消息失败 隐藏消息列表");
        if (!weakSelf.isFirstLoading) {
            weakSelf.isFirstLoading=YES;
            [weakSelf loadingCourseFunction:[SINACalendarUtils currentTimeStr]];
        }else{
            if(self.courseItemArray.count==0){
                [weakSelf loadingCourseFunction:[SINACalendarUtils currentTimeStr]];
            }
        }
    }];
    
}
//加载课程相关
-(void) loadingCourseFunction:(NSString *)dateString{
    
    [self.courseItemArray removeAllObjects];
    [self.tableView reloadData];
    //dateString=@"1511280000000";
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@?uuid=%@&searchdate=%@",baseUrl,userStuHomeCourUrl,[[SINACommonUserHelper share] getUserModel].userUid, dateString] success:^(id responseData) {
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *result = responseData[@"content"];
            if (result!=nil&&result.count>0) {
                [self.courseItemArray removeAllObjects];
                for (NSInteger i=0; i<result.count; i++) {
                    NSDictionary *dic = result[i];
                    SINAStuHomeCoursItemModel *model = [[SINAStuHomeCoursItemModel alloc]initWithDict:dic];
                    
                    [self.courseItemArray addObject:model];
                }
                //有课程数据
                SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
                
                coursItemModel.itemType=@"2";
                coursItemModel.activityStatue=@"4";
                coursItemModel.itemTime=[[SINACalendarUtils alloc] getCurrentTime:@"HH:mm"];
                
                weakSelf.noCourseStateLabel.hidden=YES;
                
                //[self.courseItemArray addObject:coursItemModel];
            }else{
                //[self.courseItemArray removeAllObjects];
                //无数据
                SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
                
                coursItemModel.itemType=@"2";
                coursItemModel.activityStatue=@"4";
                coursItemModel.itemTime=[[SINACalendarUtils alloc] getCurrentTime:@"HH:mm"];
                weakSelf.noCourseStateLabel.hidden=NO;
                // [self.courseItemArray addObject:coursItemModel];
            }
            
            
            
        }else{
            [self.courseItemArray removeAllObjects];
            //无数据
            SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
            
            coursItemModel.itemType=@"2";
            coursItemModel.activityStatue=@"4";
            coursItemModel.itemTime=[[SINACalendarUtils alloc] getCurrentTime:@"HH:mm"];
            //[self.courseItemArray addObject:coursItemModel];
            //无数据
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
            
            weakSelf.noCourseStateLabel.hidden=NO;
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error, NSInteger errCode) {
        [self.courseItemArray removeAllObjects];
        //无数据
        SINAStuHomeCoursItemModel *coursItemModel = [[SINAStuHomeCoursItemModel alloc]init];
        coursItemModel.itemTime=[[SINACalendarUtils alloc] getCurrentTime:@"HH:mm"];
        coursItemModel.itemType=@"2";
        coursItemModel.activityStatue=@"4";
        //[self.courseItemArray addObject:coursItemModel];
        [self.tableView reloadData];
        //无数据
        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"获取数据验证失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
    
}
//日历时间计算
//0 初次初始化
//1 多次噗v微信
-(void) initTimeFunction:(NSInteger)flag{
    
    [self.dateArray removeAllObjects];
    DLog(@"初始化日期数据");
    
    // 可指定日历的算法
    if (flag==0) {
        self.currentYear = [SINACalendarUtils getYear];
        self. currentMonth=[SINACalendarUtils getMonth];
        self. currentDay = [SINACalendarUtils getDay];
    }
    
    DLog(@"current year is  %ld  month is %ld  day is %ld ",self.currentYear,self.currentMonth,self.currentDay);
    NSArray * arrWeek=[NSArray arrayWithObjects:@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六", nil];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |
    NSCalendarUnitDay |NSCalendarUnitWeekday |
    NSCalendarUnitHour |NSCalendarUnitMinute |
    NSCalendarUnitSecond;
    NSDate *date = [NSDate date];
    comps = [calendar components:unitFlags fromDate:date];
    
    NSInteger week = [comps weekday];
    if(week<arrWeek.count){
        self.currentWeek = [NSString stringWithFormat:@"%@",[arrWeek objectAtIndex:week]];
    }
    NSInteger flagYear = self.currentYear;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; // 默认使用0时区，所以需要时区的转换
    
    //向前添加1年
    for (NSInteger i=1; i<=1; i++) {
        flagYear=self.currentYear-i;
        for (NSInteger j=1; j<=12; j++) {
            NSDate *nowDate = [formatter dateFromString:[NSString stringWithFormat:@"%ld年%ld月01日 00:00:00",(long)flagYear,(long)j]];
            NSInteger flagWeek = [SINACalendarUtils getFirstDayWeekForMonth:nowDate];
            DLog(@"时间 %ld年%ld月1日 %ld",(long)flagYear,(long)j,(long)flagWeek);
            if (j==2) {
                //2月份
                if (flagYear%4==0) {
                    //29天
                    for (NSInteger g=0; g<29; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                } else {
                    //28天
                    for (NSInteger g=0; g<28; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                }
            } else {
                //非2月份
                if (j==1||j==3||j==5||j==7||j==8||j==10||j==12) {
                    
                    //31天
                    for (NSInteger g=0; g<31; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                } else {
                    //30
                    for (NSInteger g=0; g<30; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                }
            }
        }
        
    }
    NSInteger currentPos = self.dateArray.count;
    switch (self.currentMonth) {
        case 1:{
            currentPos+=self.currentDay;
        }
            break;
        case 2:{
            if (self.currentYear%4==0) {
                currentPos+=31;
                currentPos+=29;
            } else {
                currentPos+=31;
                currentPos+=28;
            }
        }
            break;
        case 3:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            currentPos+=self.currentDay;
        }
            break;
        case 4:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            currentPos+=self.currentDay;
        }
            break;
        case 5:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            currentPos+=self.currentDay;
        }
            break;
        case 6:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            //5月
            currentPos+=31;
            currentPos+=self.currentDay;
        }
            break;
        case 7:{
            
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            //5月
            currentPos+=31;
            //6月
            currentPos+=30;
            currentPos+=self.currentDay;
        }
            break;
        case 8:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            //5月
            currentPos+=31;
            //6月
            currentPos+=30;
            //7月
            currentPos+=31;
            currentPos+=self.currentDay;
        }
            break;
        case 9:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            //5月
            currentPos+=31;
            //6月
            currentPos+=30;
            //7月
            currentPos+=31;
            //8月
            currentPos+=31;
            currentPos+=self.currentDay;
        }
            break;
        case 10:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            //5月
            currentPos+=31;
            //6月
            currentPos+=30;
            //7月
            currentPos+=31;
            //8月
            currentPos+=31;
            //9月
            currentPos+=30;
            currentPos+=self.currentDay;
        }
            break;
        case 11:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            //5月
            currentPos+=31;
            //6月
            currentPos+=30;
            //7月
            currentPos+=31;
            //8月
            currentPos+=31;
            //9月
            currentPos+=30;
            //10月
            currentPos+=31;
            currentPos+=self.currentDay;
        }
            break;
        case 12:{
            if (self.currentYear%4==0) {
                currentPos+=29;
            } else {
                currentPos+=28;
            }
            //1月
            currentPos+=31;
            //3月
            currentPos+=31;
            //4月
            currentPos+=30;
            //5月
            currentPos+=31;
            //6月
            currentPos+=30;
            //7月
            currentPos+=31;
            //8月
            currentPos+=31;
            //9月
            currentPos+=30;
            //10月
            currentPos+=31;
            currentPos+=30;
            currentPos+=self.currentDay;
        }
            break;
            
        default:
            break;
    }
    //向后添加20年
    for (NSInteger i=0; i<=1; i++) {
        flagYear=self.currentYear+i;
        for (NSInteger j=1; j<=12; j++) {
            NSDate *nowDate = [formatter dateFromString:[NSString stringWithFormat:@"%ld年%ld月01日 00:00:00",(long)flagYear,j]];
            NSInteger flagWeek = [SINACalendarUtils getFirstDayWeekForMonth:nowDate];
            if (j==2) {
                //2月份
                if (flagYear%4==0) {
                    //29天
                    for (NSInteger g=0; g<29; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                } else {
                    //28天
                    for (NSInteger g=0; g<28; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                }
            } else {
                //非2月份
                if (j==1||j==3||j==5||j==7||j==8||j==10||j==12) {
                    //31天
                    for (NSInteger g=0; g<31; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                } else {
                    //30
                    for (NSInteger g=0; g<30; g++) {
                        SINADateModel *model = [[SINADateModel alloc]init];
                        model.year =[NSString stringWithFormat:@"%ld",(long)flagYear];
                        model.month=[NSString stringWithFormat:@"%ld",(long)j];
                        model.day=[NSString stringWithFormat:@"%ld",g+1];
                        if (g!=0) {
                            flagWeek++;
                            if (flagWeek>=7) {
                                flagWeek=0;
                            }
                        }
                        model.week=[NSString stringWithFormat:@"%ld",(long)flagWeek];
                        [self.dateArray addObject: model];
                    }
                }
            }
        }
    }
    
    self.currentPos = currentPos;
}
-(void) initView{
    self.view.backgroundColor=baseSelectColor;
    self.mainContentView.backgroundColor=[UIColor colorWithHexString:@"#EEEEEE"];
    // 日期选择 部分
    
    
    
    UIView *headerParentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mainW, 159)];
    //[headerParentView setBackgroundColor:baseSelectColor];
    [self.mainContentView addSubview:headerParentView];
    
    CAGradientLayer *parentGradientLayer = [CAGradientLayer layer];
    parentGradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:@"#349ef7"].CGColor, (__bridge id)[UIColor colorWithHexString:@"#34d5f7"].CGColor];
    parentGradientLayer.locations = @[ @0.3, @1.0];
    parentGradientLayer.startPoint = CGPointMake(0, 0);
    parentGradientLayer.endPoint = CGPointMake(1.0, 0);
    
    if (IS_IPHONE_X) {
        parentGradientLayer.frame = CGRectMake(0, 0, mainW, CGRectGetHeight(headerParentView.frame)-20);
    }else{
        parentGradientLayer.frame = CGRectMake(0, 0, mainW, CGRectGetHeight(headerParentView.frame)-62);
    }
    [headerParentView.layer addSublayer:parentGradientLayer];
    
    
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mainW, 159)];
    //[headerView setBackgroundColor:baseSelectColor];
    [headerParentView addSubview:headerView];
    
    
    if (IS_IPHONE_X) {
        headerParentView.frame=CGRectMake(0, 0, mainW, 165);
        headerView.frame=CGRectMake(0, 20, mainW, 145);
    }else{
    }
    
    /*
     2018 5 29 改版去掉 左右切换时间按钮  UI 图设计整体修改
     */
    UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, 20, 7, 13)];
    leftImageView.image = [UIImage imageNamed:@"back2"];
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, 46, 63)];
    [leftView addSubview:leftImageView];
    //[headerView addSubview:leftView];
    
    UILabel *headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 34, mainW, 21)];
    [headerLabel setFont:[UIFont systemFontOfSize:20]];
    [headerLabel setTextColor:[UIColor whiteColor]];
    //[SINACalendarUtils getCurrentEnMonth:self.currentMonth] 英文月份
    headerLabel.text =[NSString stringWithFormat:@" %ld·%ld月",(long)self.currentYear,self.currentMonth];
    [headerLabel setTextAlignment: NSTextAlignmentCenter];
    [headerView addSubview:headerLabel];
    self.headerLabel = headerLabel;
    
    UIImageView *ritghtImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 7, 13)];
    ritghtImageView.image = [UIImage imageNamed:@"to_right2"];
    UIView *ritghtView = [[UIView alloc]initWithFrame:CGRectMake(mainW-30-13, 35, 26, 63)];
    [ritghtView addSubview:ritghtImageView];
    //[headerView addSubview:ritghtView];
    
    
    __weak typeof(self) weakSelf = self;
    [[SINAUiviewClickLiserner alloc]viewClickFunction:leftView andWithBlick:^(UIView *view) {
        if (weakSelf.currentMonth==1) {
            weakSelf.currentMonth=12;
            weakSelf.currentYear--;
        } else {
            weakSelf.currentMonth--;
        }
        headerLabel.text =[NSString stringWithFormat:@"%@  %ld",[SINACalendarUtils getCurrentEnMonth:weakSelf.currentMonth],weakSelf.currentYear];
        [weakSelf updateDateShowFunction];
        
    }];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:headerLabel andWithBlick:^(UIView *view) {
        DLog(@"首页面日期选择");
        [self showHomeTimeSelect];
        
    }];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:ritghtView andWithBlick:^(UIView *view) {
        if (weakSelf.currentMonth==12) {
            weakSelf.currentMonth=1;
            weakSelf.currentYear++;
        } else {
            weakSelf.currentMonth++;
        }
        headerLabel.text =[NSString stringWithFormat:@"%@  %ld",[SINACalendarUtils getCurrentEnMonth:weakSelf.currentMonth],(long)weakSelf.currentYear];
        [weakSelf updateDateShowFunction];
    }];
    
    
    
    
    self.headerDateItemUIview.frame=CGRectMake(mainW/2-(CGRectGetHeight(headerView.frame)-CGRectGetMaxY(headerLabel.frame)-25)/2, CGRectGetMaxY(headerLabel.frame)+15, CGRectGetHeight(headerView.frame)-CGRectGetMaxY(headerLabel.frame)-25, CGRectGetHeight(headerView.frame)-CGRectGetMaxY(headerLabel.frame)-25);
    [headerView addSubview: self.headerDateItemUIview];
    
    
    //[SINACircularBeadUtils makeCircularView:self.headerDateItemUIview];
    
    self.currentDayLabel.frame=CGRectMake(mainW/2-50, CGRectGetMaxY(headerLabel.frame)+25, 100, 21);
    self.currentDayLabel.textColor=[UIColor colorWithHexString:@"#878787"];
    self.currentDayLabel.textAlignment=NSTextAlignmentCenter;
    self.currentDayLabel.font = [UIFont systemFontOfSize:16];
    self.currentDayLabel.layer.zPosition=4;
    //[headerView addSubview:self.currentDayLabel];
    
    self.currentTimeLabel.frame=CGRectMake(mainW/2-50, CGRectGetMaxY(self.currentDayLabel.frame), 100, 21);
    self.currentTimeLabel.textColor=baseSelectColor;
    self.currentTimeLabel.textAlignment=NSTextAlignmentCenter;
    self.currentTimeLabel.font = [UIFont systemFontOfSize:18];
    self.currentTimeLabel.layer.zPosition=4;
    //[headerView addSubview:self.currentTimeLabel];
    
    //2018 5 29 修改日期样式
    self.headerDateItemUIview.frame=CGRectMake(14, CGRectGetMaxY(headerLabel.frame)+15, mainW-14*2, CGRectGetHeight(headerView.frame)-CGRectGetMaxY(headerLabel.frame)-49);
    CGRect headerDateTimeFrame = self.headerDateItemUIview.frame;
    if (IS_IPHONE_X) {
        headerDateTimeFrame.size.height=headerDateTimeFrame.size.height+15;
    }else if (UI_IS_IPHONE6PLUS){
        headerDateTimeFrame.size.height=headerDateTimeFrame.size.height+5;
    }
    self.headerDateItemUIview.frame = headerDateTimeFrame;
    [SINACircularBeadUtils makeCircularBead:6 andView:self.headerDateItemUIview];
    
    //日期指示线
    UIView *dateDiviView = [[UIView alloc]init];
    dateDiviView.backgroundColor=[UIColor colorWithHexString:@"349ef7"];
    dateDiviView.frame = CGRectMake(
                                    mainW/2-14, CGRectGetMaxY(self.headerDateItemUIview.frame)-3,
                                    28,
                                    2);
    self.collectionView.layer.zPosition=7;
    [headerView addSubview: dateDiviView];
    
    
    self.currentTimeLabel.text=[NSString stringWithFormat:@"%ld",(long)self.currentDay];
    self.currentDayLabel.text=[SINACalendarUtils getCurrentEnDay:self.currentDay];
    
    
    
    //日期滑动选择部分
    self.collectionView.frame=CGRectMake(24, CGRectGetMaxY(headerLabel.frame)+13, mainW-24*2, CGRectGetHeight(headerView.frame)-CGRectGetMaxY(headerLabel.frame)-45);
    self.collectionView.backgroundColor=[UIColor clearColor];
    self.collectionView.delegate=self;
    self.collectionView.dataSource=self;
    self.collectionView.showsHorizontalScrollIndicator=NO;
    self.collectionView.showsVerticalScrollIndicator=NO;
    self.collectionView.layer.zPosition=5;
    [self.collectionView registerClass:[SINAHomeDateItemCollectionViewCell class] forCellWithReuseIdentifier:identifier];
    
    
    [headerView addSubview: self.collectionView];
    
    
    if (IS_IPHONE_X) {
        //iphonex 适配日期选择部分
        self.collectionView.frame=CGRectMake(24, CGRectGetMaxY(headerLabel.frame)+13, mainW-24*2, CGRectGetHeight(headerView.frame)-CGRectGetMaxY(headerLabel.frame)-40);
    }else if(UI_IS_IPHONE6PLUS){
        self.collectionView.frame=CGRectMake(24, CGRectGetMaxY(headerLabel.frame)+13, mainW-24*2, CGRectGetHeight(headerView.frame)-CGRectGetMaxY(headerLabel.frame)-30);
    }
    
    
    UIImageView *headerDiviView = [[UIImageView alloc]init];
    headerDiviView.frame=CGRectMake(mainW/2-63/2, CGRectGetMaxY(headerView.frame)-20, 63, 4);
    headerDiviView.image = [UIImage imageNamed:@"headermsgdivi"];
    
    [self.mainContentView addSubview:headerDiviView];
    if (IS_IPHONE_X) {
        headerDiviView.frame=CGRectMake(mainW/2-63/2, CGRectGetMaxY(headerView.frame)-5, 63, 4);
    }else if(UI_IS_IPHONE6PLUS){
        headerDiviView.frame=CGRectMake(mainW/2-63/2, CGRectGetMaxY(headerView.frame)-15, 63, 4);
    }
    
    
    
    SMSwipeView *swipeView =[[SMSwipeView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame)+5, mainW, 64)];
    swipeView.delegate=self;
    swipeView.isStackCard=YES;
    
    swipeView.hidden = YES;
    self.swipeView = swipeView;
    [self.mainContentView addSubview:swipeView];
    
    UIView *currentTimeView=[[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(swipeView.frame)+15, mainW,21)];
    UILabel *weekLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, mainW-30, 21)];
    [weekLabel setFont:[UIFont systemFontOfSize:18]];
    [weekLabel setTextColor:[UIColor blackColor]];
    weekLabel.text =self.currentWeek;
    [weekLabel setTextAlignment: NSTextAlignmentLeft];
    [currentTimeView addSubview:weekLabel];
    
    UILabel *yearLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 0, mainW-90, 21)];
    [yearLabel setFont:[UIFont systemFontOfSize:14]];
    [yearLabel setTextColor:[UIColor colorWithHexString:@"#878787"]];
    yearLabel.text =[NSString stringWithFormat:@"%ld-%ld-%ld",(long)self.currentYear,(long)self.currentMonth,(long)self.currentDay];
    [yearLabel setTextAlignment: NSTextAlignmentLeft];
    [currentTimeView addSubview:yearLabel];
    
    currentTimeView.backgroundColor =[UIColor colorWithHexString:@"#eeeeee"];
    //[self.mainContentView addSubview:currentTimeView];
    
    
    //2018年6月 新版消息UI设计
    
    NSMutableArray *items = [NSMutableArray new];
    
    //设置消息卡片浏览器
    self.msgCardSwitch = [[XLCardSwitch alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerDiviView.frame)-4,mainW , 116)];
    self.msgCardSwitch.isAnimation =NO;
    self.msgCardSwitch.pagetype=CARDMSGPAGE;
    self.msgCardSwitch.items = items;
    self.msgCardSwitch.delegate = self;
    //分页切换
    self.msgCardSwitch.pagingEnabled = true;
    //设置初始位置，默认为0
    self.msgCardSwitch.selectedIndex = 0;
    
    [self.mainContentView addSubview:self.msgCardSwitch];
    
    self.msgCardSwitch.switchItemClickBlock = ^(UIView *view, NSInteger index) {
        DLog(@"msg item click index  is %ld",(long)index);
        SINAMsgDetaileViewController *controll = [[SINAMsgDetaileViewController alloc]initWithNibName:@"SINAMsgDetaileViewController" bundle:nil];
        XLCardItem *item = weakSelf.headeMsgArray[index];
        controll.model=item.msgItemModel;
        controll.hidesBottomBarWhenPushed=YES;
        [weakSelf.navigationController pushViewController:controll animated:YES];
        
    };
    
    
    UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.msgCardSwitch.frame)+5, mainW, mainH-CGRectGetMaxY(self.msgCardSwitch.frame)-58)];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    tableView.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator=NO;
    tableView.showsHorizontalScrollIndicator=NO;
    [self.mainContentView addSubview:tableView];
    self.tableView = tableView;
    
    self.currentSelectTime =[SINACalendarUtils currentTimeStr];
    
    [self.mainContentView addSubview:self.noDataUiLabel];
    
    [[SINAUiviewClickLiserner alloc] viewClickFunction:self.noDataUiLabel andWithBlick:^(UIView *view) {

        [weakSelf loadingCourseFunction:self.currentSelectTime];
    }];
    
    self.swipeView.swipItemBlock = ^(NSInteger index) {
        DLog(@"滑动切换 %ld",(long)index);
        
        SINAMsgItemModel *msgModel = weakSelf.headeMsgArray[index-1];
        if ([weakSelf.db open]) {
            BOOL b = [weakSelf.db executeUpdate:@"update t_stu_msg SET msgread = ? WHERE msgid = ?",[NSString stringWithFormat:@"%@",@"2"],msgModel.msgId];
            
            if (b) {
                DLog(@"update success ");
            } else {
                DLog(@"update error ");
            }
        }
        if (weakSelf.headeMsgArray.count-1<=index-1) {
            DLog(@"加载新的数据 ");
    
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [weakSelf loadingHeaderMsgFunction];
            });
            
        }
    };
    
    for (NSInteger i=0; i<self.dateArray.count; i++) {
        SINADateModel *model =self.dateArray[i];
        if ([model.year integerValue ]==self.currentYear &&[model.month integerValue]==self.currentMonth&&[model.day integerValue]==self.currentDay) {
            DLog(@"current %@-%@-%@",model.year,model.month,model.day);
            self.currentPos=i+1;
            break;
        }
    }
    DLog(@"currentPos is %ld",(long)self.currentPos);
    
    [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.contentOffset.y) animated:YES];
    [self.collectionView setContentOffset:CGPointMake((self.currentPos-3)*self.dateItemWidth, self.collectionView.contentOffset.y) animated:YES];
    
    
    
    //添加按钮
    UIImageView *addActivityImageView = [[UIImageView alloc]init];
    addActivityImageView.frame=CGRectMake(mainW-72-10, mainH-60-72, 72, 72);
    addActivityImageView.image = [UIImage imageNamed:@"add_activity"];
    UIView *addActivityUIView = [[UIView alloc]initWithFrame:CGRectMake(mainW-100, mainH-60-72, 100, 72)];
    addActivityUIView.backgroundColor = [UIColor clearColor];
    self.addActivityUIView = addActivityUIView;
    self.addActivityImageView=addActivityImageView;
    [self.mainContentView addSubview:addActivityImageView];
    [self.mainContentView addSubview:addActivityUIView];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:addActivityUIView andWithBlick:^(UIView *view) {
        DLog(@"添加活动");
        if ([super checkApproveIdent]) {
            SINAStuActivityAddItemViewController *addItemController = [[SINAStuActivityAddItemViewController alloc]initWithNibName:@"SINAStuActivityAddItemViewController" bundle:nil];
            addItemController.hidesBottomBarWhenPushed=YES;
            weakSelf.navigationController.navigationBar.hidden=NO;
            [weakSelf.navigationController pushViewController:addItemController animated:YES];
        }
        
    }];
    
    if (IS_IPHONE_X) {
        addActivityImageView.frame=CGRectMake(mainW-72-10, mainH-60-92, 72, 72);
    }
    
    
    UILabel *noCourseStateLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.msgCardSwitch.frame)+5, mainW, 44)];
    noCourseStateLabel.text=@"暂无课程活动数据 点击刷新";
    noCourseStateLabel.font=[UIFont systemFontOfSize:13];
    noCourseStateLabel.textAlignment=NSTextAlignmentCenter;
    noCourseStateLabel.textColor=[UIColor colorWithHexString:@"#2e2e2e"];
    noCourseStateLabel.hidden=YES;
    self.noCourseStateLabel=noCourseStateLabel;
    [self.mainContentView addSubview:noCourseStateLabel];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:noCourseStateLabel andWithBlick:^(UIView *view) {
        DLog(@"刷新课程");
        [weakSelf loadingCourseFunction:self.currentSelectTime];
    }];
    
}

-(NSMutableArray *)courseItemArray{
    if (!_courseItemArray) {
        _courseItemArray = [[NSMutableArray alloc]init];
    }
    return _courseItemArray;
}
-(NSMutableArray *)dateArray{
    if (!_dateArray) {
        _dateArray=[[NSMutableArray alloc]init];
    }
    return _dateArray;
}
-(UILabel *)currentTimeLabel{
    if (!_currentTimeLabel) {
        _currentTimeLabel=[[UILabel alloc]init];
    }
    
    return _currentTimeLabel;
}
-(UILabel *)noDataUiLabel{
    if (!_noDataUiLabel) {
        _noDataUiLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 20, mainW, mainH)];
        _noDataUiLabel.textAlignment=NSTextAlignmentCenter;
        _noDataUiLabel.text=@"暂无数据 点击刷新";
        _noDataUiLabel.textColor=[UIColor colorWithHexString:@"#878787"];
        _noDataUiLabel.font=[UIFont systemFontOfSize:18];
        _noDataUiLabel.hidden=YES;
    }
    return _noDataUiLabel;
}
-(UILabel *)currentDayLabel{
    if (!_currentDayLabel) {
        _currentDayLabel=[[UILabel alloc]init];
    }
    
    return _currentDayLabel;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //自动网格布局
        SINAStuDateItemFlowLayout * flowLayout = [[SINAStuDateItemFlowLayout alloc]init];
        //设置滚动方向
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        //设置单元格大小
        flowLayout.itemSize = CGSizeMake(self.dateItemWidth, self.dateItemWidth+20);
        //列距
        flowLayout.minimumInteritemSpacing = 0;
        //行距
        flowLayout.minimumLineSpacing = 0;
        flowLayout.offsetpoint = CGPointMake(0, 0.f);
        //网格布局
        _collectionView = [[UICollectionView alloc]initWithFrame:self.mainContentView.frame collectionViewLayout:flowLayout];
        //注册cell
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];
        _collectionView.userInteractionEnabled=YES;
        _collectionView.dataSource = self;
        _collectionView.delegate=self;
    }
    return _collectionView;
    
}

-(UIView *)headerDateItemUIview{
    if (!_headerDateItemUIview) {
        _headerDateItemUIview = [[UIView alloc]initWithFrame:CGRectMake(mainW/2-50, 100, 100, 100)];
        _headerDateItemUIview.backgroundColor=[UIColor whiteColor];
    }
    return _headerDateItemUIview;
}

//更新时间显示
-(void) updateDateShowFunction{
    NSString * dateString1 =[NSString stringWithFormat:@"%ld-%ld-%ld",(long)self.currentYear,(long)self.currentMonth,(long)self.currentDay];
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd";
    NSDate * date = [df dateFromString:dateString1];
    
    self.currentSelectTime =[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]];
    
    //[self loadingCourseFunction:self.currentSelectTime];
    
    [self loadingHeaderMsgFunction];
    
    for (NSInteger i=0; i<self.dateArray.count; i++) {
        SINADateModel *model =self.dateArray[i];
        if ([model.year integerValue ]==self.currentYear &&[model.month integerValue]==self.currentMonth&&[model.day integerValue]==self.currentDay) {
            self.currentPos=i;
            break;
        }
    }
    DLog(@"currentPos is %ld",(long)self.currentPos);
    [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.contentOffset.y) animated:YES];
    [self.collectionView setContentOffset:CGPointMake((self.currentPos-3)*self.dateItemWidth, self.collectionView.contentOffset.y) animated:YES];
    
    
}

-(UITableViewCell*)SMSwipeGetView:(SMSwipeView *)swipe withIndex:(int)index{
    static NSString * identify=@"testIndentify";
    UITableViewCell * cell=[self.swipeView dequeueReusableUIViewWithIdentifier:identify];
    //    if (cell==nil) {
    //        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    //    }else{
    //        DLog(@"%@",@"not nil");
    //    }
    //
    //    cell.textLabel.text=[NSString stringWithFormat:@"这是一个很神奇的效果%d",index];
    //    cell.textLabel.textColor=[UIColor whiteColor];
    //    cell.backgroundColor=baseSelectColor;
    //    cell.imageView.image=[UIImage imageNamed:@"choose_gou"];
    //    cell.layer.cornerRadius=10;
    
    
    
    if (cell == nil) {
        cell= [[[NSBundle mainBundle]loadNibNamed:@"SINAHeaderMsgItemTableViewCell" owner:nil options:nil] firstObject];
        
    }
    
    if (self.headeMsgArray.count!=0) {
        SINAMsgItemModel *msgItemModel = self.headeMsgArray[index];
        
        ((SINAHeaderMsgItemTableViewCell*)cell).msgItemModel = msgItemModel;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //cell.layer.cornerRadius=10;
        cell.backgroundColor=baseSelectColor;
    }
    
    
    
    return cell;
}
-(NSInteger)SMSwipeGetTotaleNum:(SMSwipeView *)swipe{
    return self.headeMsgArray.count;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    // 获取开始拖拽时tableview偏移量
    _oldY = self.tableView.contentOffset.y;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //    static NSInteger currentIndex = 0;
    
    if ([scrollView isEqual: self.tableView]) {
        if (self.tableView.contentOffset.y > _oldY) {
            // 上滑
            DLog(@"上滑");
            if (!self.isMoveIcon && self.addActivityUIView.hidden==NO) {
                self.isMoveIcon=YES;
                self.addActivityUIView.hidden=NO;
                CGRect preFrame = self.addActivityImageView.frame;
                NSInteger curY= preFrame.origin.y;
                preFrame.origin.y = curY+mainH/5;
                [UIView animateWithDuration:0.25 animations:^{
                    self.addActivityImageView.frame = preFrame;
                } completion:^(BOOL finished) {
                    self.isMoveIcon=NO;
                    self.addActivityUIView.hidden=YES;
                }];
            }
            
        }
        else{
            // 下滑
            DLog(@"下滑");
            if (!self.isMoveIcon && self.addActivityUIView.hidden==YES) {
                self.isMoveIcon=YES;
                self.addActivityUIView.hidden=NO;
                CGRect preFrame = self.addActivityImageView.frame;
                NSInteger curY= preFrame.origin.y;
                preFrame.origin.y = curY-mainH/5-20;
                [UIView animateWithDuration:0.45 animations:^{
                    self.addActivityImageView.frame = preFrame;
                } completion:^(BOOL finished) {
                    CGRect preFrame = self.addActivityImageView.frame;
                    NSInteger curY= preFrame.origin.y;
                    preFrame.origin.y = curY+20;
                    [UIView animateWithDuration:0.2 animations:^{
                        self.addActivityImageView.frame = preFrame;
                    } completion:^(BOOL finished) {
                        self.isMoveIcon=NO;
                    }];
                    
                }];
            }
        }
    }else{
        
        NSInteger index=scrollView.contentOffset.y;
        CGRect visibleRect = (CGRect){.origin = self.collectionView.contentOffset, .size = self.collectionView.bounds.size};
        CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
        NSIndexPath *visibleIndexPath = [self.collectionView indexPathForItemAtPoint:visiblePoint];
        DLog(@"scrollViewDidScroll - :P %ld ---- 当前位置 %ld",(long)index,(long)visibleIndexPath.row);
        
        SINADateModel *model =self.dateArray[visibleIndexPath.row];
        DLog(@"当前时间 %@-%@-%@ %@",model.year,model.month,model.day,model.week);
        
        self.currentTimeLabel.text=model.day;
        self.currentDayLabel.text=[SINACalendarUtils getCurrentEnDay:[model.week intValue]];
        
        //[self.itemTool itemScrollToPositionWithIndex:currentIndex isJump:YES];
        
    }
}

#pragma mark - deleDate
//有多少的分组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
    
}
//每个分组里有多少个item
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dateArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //根据identifier从缓冲池里去出cell
    //    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    //    cell.backgroundColor = [UIColor orangeColor];
    SINAHomeDateItemCollectionViewCell  *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    cell.backGrouncWidth=self.dateItemWidth;
    
    cell.pos =indexPath.row;
    cell.model=self.dateArray[indexPath.row];
    
    cell.dateItemCollectViewBlock = ^(SINADateModel *model, NSInteger pos) {
        DLog(@"select date dateItemCollectViewBlockis %ld",(long)indexPath.row);
    };
    [[SINAUiviewClickLiserner alloc]viewClickFunction:cell andWithBlick:^(UIView *view) {
        DLog(@"select date ");
        self.currentPos = indexPath.row;
        SINADateModel *model =self.dateArray[indexPath.row];
        NSDateFormatter * df = [[NSDateFormatter alloc] init];
        df.dateFormat = @"yyyy-MM-dd";
        NSString * dateString1 =[NSString stringWithFormat:@"%@-%@-%@",model.year,model.month,model.day];
        NSDate * date = [df dateFromString:dateString1];
        self.currentSelectTime =[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]];
        
        [self.collectionView setContentOffset:CGPointMake((self.currentPos-2)*self.dateItemWidth, self.collectionView.contentOffset.y) animated:YES];
        //刷新首页面数据
        //[self loadingCourseFunction:self.currentSelectTime];
        [self loadingHeaderMsgFunction];
    }];
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"select date is %ld",(long)indexPath.row);
}
//返回这个UICollectionViewCell是否可以被选择
-( BOOL )collectionView:( UICollectionView *)collectionView shouldSelectItemAtIndexPath:( NSIndexPath *)indexPath{
    return YES ;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        
        
        CGPoint originalTargetContentOffset = CGPointMake(targetContentOffset->x, targetContentOffset->y);
        CGPoint targetCenter = CGPointMake(originalTargetContentOffset.x + CGRectGetWidth(self.collectionView.bounds)/2, CGRectGetHeight(self.collectionView.bounds) / 2);
        NSIndexPath *indexPath = nil;
        NSInteger i = 0;
        while (indexPath == nil) {
            targetCenter = CGPointMake(originalTargetContentOffset.x + CGRectGetWidth(self.collectionView.bounds)/2 + self.dateItemWidth*i, CGRectGetHeight(self.collectionView.bounds) / 2);
            indexPath = [self.collectionView indexPathForItemAtPoint:targetCenter];
            i++;
        }
        if (indexPath!=nil) {
            SINADateModel *model =self.dateArray[indexPath.row];
            
            
            //self.currentTimeLabel.text=model.day;
            //self.currentDayLabel.text=[SINACalendarUtils getCurrentEnDay:[model.week intValue]];
            
            self.currentMonth = [model.month integerValue];
            self.currentYear = [model.year integerValue];
            self.headerLabel.text =[NSString stringWithFormat:@" %ld·%ld月",(long)self.currentYear,self.currentMonth];
            DLog(@"date current select is %ld",(long)indexPath.row);
            NSDateFormatter * df = [[NSDateFormatter alloc] init];
            df.dateFormat = @"yyyy-MM-dd";
            
            
            
            NSString * dateString1 =[NSString stringWithFormat:@"%@-%@-%@",model.year,model.month,model.day];
            NSDate * date = [df dateFromString:dateString1];
            
            self.currentSelectTime =[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]];
            [self loadingCourseFunction:self.currentSelectTime];
            DLog(@"date current select is %@年%@月%@日",model.year,model.month,model.day);
        }
        //self.selectedIndex = indexPath;
        
        //这里用attributes比用cell要好很多，因为cell可能因为不在屏幕范围内导致cellForItemAtIndexPath返回nil
        UICollectionViewLayoutAttributes *attributes = [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
        if (attributes) {
            *targetContentOffset = CGPointMake(attributes.center.x - CGRectGetWidth(self.collectionView.bounds)/2, originalTargetContentOffset.y);
        } else {
            DLog(@"center is %@; indexPath is {%@, %@}; cell is %@",NSStringFromCGPoint(targetCenter), @(indexPath.section), @(indexPath.item), attributes);
        }
        
    }
    
}






//课程相关

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.courseItemArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SINAStuHomeCoursItemModel *model = self.courseItemArray[indexPath.row];
    NSString *iteType = model.itemType;
    
    
    if ([iteType integerValue]==1) {
        DLog(@"有课程");
        
        SINAStueHomeCourseItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINAStueHomeCourseItemTableViewCell"];
        
        if (cell == nil) {
            cell= [[[NSBundle mainBundle]loadNibNamed:@"SINAStueHomeCourseItemTableViewCell" owner:nil options:nil] firstObject];
            
        }
        cell.pos=indexPath.row;
        cell.totalNumber=self.courseItemArray.count;
        
        cell.itemCellBlock = ^(NSInteger pos, NSInteger flag, SINAStuHomeCoursItemModel *itemModel) {
            [self coureItemClickFunction:itemModel andWithFlagIndex:flag];
        };
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell ;
        
    } else   {
        
        SINAStueHomeActivityItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINAStueHomeActivityItemTableViewCell"];
        
        if (cell == nil) {
            cell= [[[NSBundle mainBundle]loadNibNamed:@"SINAStueHomeActivityItemTableViewCell" owner:nil options:nil] firstObject];
            
        }
        cell.position = indexPath.row;
        cell.itemCellBlock = ^(NSInteger pos, BOOL isShow,SINAStuHomeCoursItemModel *itemModel) {
            [self.courseItemArray replaceObjectAtIndex:pos withObject:itemModel];
            NSIndexPath *curIndexPath=[NSIndexPath indexPathForRow:pos inSection:0];
            
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:curIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView scrollToRowAtIndexPath:curIndexPath atScrollPosition:pos animated:YES];
        };
        
        //删除相关
        cell.itemDeleteBlock = ^(NSInteger pos, BOOL isShow, SINAStuHomeCoursItemModel *itemModel) {
            
            [self deleteActivity:itemModel andWithPos:pos];
            
        };
        __weak typeof(self) weakSelf = self;
        //添加项目
        cell.addItemBlock = ^(NSInteger pos) {
            DLog(@"添加项目 ");
            SINAStuActivityAddItemViewController *addItemController = [[SINAStuActivityAddItemViewController alloc]initWithNibName:@"SINAStuActivityAddItemViewController" bundle:nil];
            addItemController.hidesBottomBarWhenPushed=YES;
            weakSelf.navigationController.navigationBar.hidden=NO;
            [weakSelf.navigationController pushViewController:addItemController animated:YES];
        };
        //活动详情
        cell.activityDesItemBlock = ^(NSInteger pos,NSInteger flag, SINAStuHomeCoursItemModel *itemModel) {
            if (flag==1) {
                [weakSelf toActivityDesPageFunction:itemModel];
            }else if (flag==2){
                SINAStuActivityLeaveWordViewController *addItemController = [[SINAStuActivityLeaveWordViewController alloc]initWithNibName:@"SINAStuActivityLeaveWordViewController" bundle:nil];
                addItemController.hidesBottomBarWhenPushed=YES;
                addItemController.model = itemModel;
                weakSelf.navigationController.navigationBar.hidden=NO;
                [weakSelf.navigationController pushViewController:addItemController animated:YES];
            }else if (flag==3){
                [weakSelf toActivityDesPageFunction:itemModel];
            }
            
        };
        //完成
        cell.finishItemBlock = ^(NSInteger pos, NSInteger flag, SINAStuHomeCoursItemModel *itemModel) {
            [self finishActivity:itemModel andWithPos:pos];
        };
        
        //取消组队
        cell.itemCancleBlock = ^(NSInteger pos, BOOL isShow, SINAStuHomeCoursItemModel *itemModel) {
            [self canleTeamActivity:itemModel andWithPos:pos];
        };
        
        cell.pos=indexPath.row;
        cell.totalNumber=self.courseItemArray.count;
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell ;
    }
    
}

-(void) toActivityDesPageFunction:(SINAStuHomeCoursItemModel*)itemModel {
    SINAStuActivityDesViewController *addItemController = [[SINAStuActivityDesViewController alloc]initWithNibName:@"SINAStuActivityDesViewController" bundle:nil];
    addItemController.model = itemModel;
    addItemController.hidesBottomBarWhenPushed=YES;
    self.navigationController.navigationBar.hidden=NO;
    [self.navigationController pushViewController:addItemController animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SINAStuHomeCoursItemModel *model = self.courseItemArray[indexPath.row];
    NSString *iteType = model.itemType;
    if ([model.courseTitle isEqualToString:@"健美操"]) {
        DLog(@"");
    }
    if ([iteType integerValue]==1) {
        return 104;
    }else if ([iteType integerValue]==2) {
        if ([model.activityStatue integerValue]==1&&!model.activityShowDetaile) {
            //组队发起 未组队成功  不显示想组队的人
            //活动未开始
            NSInteger activityStartTime = [model.activityStartTime integerValue];
            NSInteger activityEndTime = [model.activityStopTime integerValue];
            //当前时间
            NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
            if (currentTime<activityStartTime) {
                //活动未开始
                return 100+65-10;
            }else if (currentTime>=activityStartTime&&currentTime<=activityEndTime) {
                //活动中
                return 100+65-10;
            }else if(currentTime>=activityEndTime&&currentTime<=(activityEndTime+30*60*1000)){
                //活动开始 以及结束后的半小时
                return 105+8;
            }else{
                //超时
                return 105+8;
            }
        } else if ([model.activityStatue integerValue]==1&&model.activityShowDetaile) {
            //组队发起 未组队成功  显示想组队的人
            //            if([UIScreen mainScreen].bounds.size.height == 480){
            //                // 1 判断是否为3.5inch      320*480
            //                return 106+216;
            //            }else if([UIScreen mainScreen].bounds.size.height == 568){
            //                // 判断是否为4inch        640*1136
            //                return 106+216;
            //            }else if([UIScreen mainScreen].bounds.size.height == 667){
            //                //3 判断是否为4.7inch   375*667   750*1334   iphone8
            //                return 106+216+12;
            //            }else{
            //                //4 判断是否为5.5inch   414*1104   1242*2208 iphone8 plus
            //                return 106+232+12;
            //            }
            
            if (UI_IS_IPHONE6PLUS) {
                return 106+232+12+10;
            }else{
                return 106+216+14;
            }
            
        }else if ([model.activityStatue integerValue]==2) {
            //组队成功
            return 156;
        }else if ([model.activityStatue integerValue]==3&&!model.activityShowDetaile) {
            //组队成功 组队事务完成 不显示详情
            return 112;
        }else if ([model.activityStatue integerValue]==3&&model.activityShowDetaile) {
            //组队成功 组队事务完成 显示详情
            NSInteger flag = model.itemHeight;
            if (flag==0) {
                return 108;
            } else {
                return flag+8;
            }
            
        }else if ([model.activityStatue integerValue]==3){
            return 100;
        }else {
            return 106;
        }
        
    }
    else{
        return 106;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    //    NSInteger index = indexPath.row;
    
    
    //    SINAAskDetailViewController *controller = [[SINAAskDetailViewController alloc]init];
    //    controller.model = model;
    //    [self.navigationController pushViewController:controller animated:YES];
    
}
//- (NSArray*)tableView:(UITableView*)tableView editActionsForRowAtIndexPath:(NSIndexPath*)indexPath
//
//{
//    
//    UITableViewRowAction*rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction*_Nonnullaction,NSIndexPath*_NonnullindexPath) {
//        
//        DLog(@"删除要实现的代码");
//        
//    }];
//    
//    UITableViewRowAction*rowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"标为已读" handler:^(UITableViewRowAction*_Nonnullaction,NSIndexPath*_NonnullindexPath) {
//        
//        DLog(@"标为已读要实现的代码");
//        
//    }];
//    
//    //自定义颜色
//    
////    rowAction.backgroundColor=RGB(231,96,35);
////
////    rowAction1.backgroundColor=RGB(150,150,150);
////
//    NSArray*arr =@[rowAction,rowAction1];
//    
//    return arr;
//    
//}

//删除活动
-(void)deleteActivity:(SINAStuHomeCoursItemModel *)itemModel andWithPos:(NSInteger)pos{
    
    
    WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:@"确定删除" sureBtn:@"确定" cancleBtn:@"取消"];
    alertView.resultIndex = ^(NSInteger index) {

        [self startLoading];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        //参数一 当前活动UUID
        [dict setObject:itemModel.activityUid forKey:@"uuid"];
        //参数二 当前登录用户名
        [dict setObject:[[SINACommonUserHelper share] getUserModel].userRealName forKey:@"userName"];
        //参数三 当前活动名称
        if(itemModel.activityTitle!=nil&&![itemModel.activityTitle isEqualToString:@""]&&![itemModel.activityTitle isEqualToString:@"(null)"]){
            [dict setValue:itemModel.activityTitle forKey:@"activityName"];
        }
        if(![itemModel.partneruuid isKindOfClass:[NSNull class]]||(itemModel.partneruuid!=nil||![itemModel.partneruuid isEqualToString:@""]||![itemModel.partneruuid isEqualToString:@"(null)"])){
            //参数四 组队对方uuid
            [dict setValue:itemModel.partneruuid forKey:@"partnerUUID"];
        }
        
        //    [dict setObject:self.identitys forKey:@"identity"];
        NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
        [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
        WeakSelf;
        [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userStuHomeDeleteActivityUrl] withParamters:dict2 success:^(id responseData) {
            NSString *code = responseData[@"code"];
            [weakSelf stopLoading];
            if ([code isEqualToString:@"1000"]) {
                [YPXToastView showToastViewWithText:@"删除成功" andDuration:1 andParentView:self.collectionView];
                [self.courseItemArray removeObjectAtIndex:pos];
                
                [self.tableView reloadData];
                if(pos!=0){
                    NSIndexPath *curIndexPath=[NSIndexPath indexPathForRow:pos-1 inSection:0];
                    
                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:curIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                    [self.tableView scrollToRowAtIndexPath:curIndexPath atScrollPosition:pos-1 animated:YES];
                }
            }else{
                NSString *message =responseData[@"message"];
                WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
                [alertView showXLAlertView];
            }
            
        } failure:^(NSError *error, NSInteger errCode) {
            //DLog(@"加载 失败  %@ ",error.debugDescription);
            [weakSelf stopLoading];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"删除验证失败" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }];
    };
    [alertView showXLAlertView];
    
    
}

//完成活动
-(void)finishActivity:(SINAStuHomeCoursItemModel *)itemModel andWithPos:(NSInteger)pos{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    
    NSMutableArray *targetArray=itemModel.teamTargetArray;
    BOOL isFinishAllTarget=YES;
    
    for (NSInteger i=0; i<targetArray.count; i++) {
        SINAStuActivityTargetModel *targetModel = targetArray[i];
        if (targetModel.endTime==0) {
            isFinishAllTarget =NO;
        }
    }
    
    if (!isFinishAllTarget) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"还有未完成的小目标" sureBtn:@"去查看"
                                                             cancleBtn:nil];
        alertView.resultIndex = ^(NSInteger index) {
            
        };
        [alertView showXLAlertView];
        return;
    }
    
    
    //参数一 当前活动UUID
    [dict setObject:itemModel.activityUid forKey:@"uuid"];
    //参数二 当前登录用户名
    [dict setObject:[[SINACommonUserHelper share] getUserModel].userRealName forKey:@"userName"];
    //参数三 当前活动名称
    if(itemModel.activityTitle!=nil&&![itemModel.activityTitle isEqualToString:@""]&&![itemModel.activityTitle isEqualToString:@"(null)"]){
        [dict setValue:itemModel.activityTitle forKey:@"activityName"];
    }
    if(itemModel.partneruuid!=nil&&![itemModel.partneruuid isEqualToString:@""]&&![itemModel.partneruuid isEqualToString:@"(null)"]){
        //参数四 组队对方uuid
        [dict setValue:itemModel.partneruuid forKey:@"partnerUUID"];
    }
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userStuHomeFinishActivityUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        if ([code isEqualToString:@"1000"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"提交成功" sureBtn:@"去查看"
                                                                 cancleBtn:nil];
            alertView.resultIndex = ^(NSInteger index) {
                
                //创建通知
                NSNotification *notification =[NSNotification notificationWithName:@"stuActivityAddFindOther" object:nil userInfo:dict];
                // 通过 通知中心 发送 通知
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
                
            };
            [alertView showXLAlertView];
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"网络异常" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}


- (void) loadRefreshView
{
    // 下拉刷新
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@""];
    [self.refreshControl addTarget:self action:@selector(loadData) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:self.refreshControl];
    
}

// 结束刷新
- (void) endRefreshControl
{
    [self.refreshControl endRefreshing];
}

// 刷新的回调方法
- (void) loadData
{
    DLog(@"下拉刷新数据 ");
    [self endRefreshControl];
    
    [self loadingCourseFunction:self.currentSelectTime];
}

//取消组队
-(void)canleTeamActivity:(SINAStuHomeCoursItemModel *)itemModel andWithPos:(NSInteger)pos{
    
    WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:@"确定取消组队？" sureBtn:@"确定" cancleBtn:@"取消"];
    alertView.resultIndex = ^(NSInteger index) {
 
        [self startLoading];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        //参数一 当前活动UUID
        [dict setObject:itemModel.activityUid forKey:@"uuid"];
        
        //参数二 当前登录用户名
        [dict setObject:[[SINACommonUserHelper share] getUserModel].userRealName forKey:@"userName"];
        //参数三 当前活动名称
        [dict setValue:itemModel.activityTitle forKey:@"activityName"];
        //参数四 组队对方uuid
        [dict setValue:itemModel.partneruuid forKey:@"partnerUUID"];
        
        //    [dict setObject:self.identitys forKey:@"identity"];
        NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
        [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
        WeakSelf;
        [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userActivityCancleUrl] withParamters:dict2 success:^(id responseData) {
            NSString *code = responseData[@"code"];
            [weakSelf stopLoading];
            if ([code isEqualToString:@"1000"]) {
                [YPXToastView showToastViewWithText:@"取消组队成功" andDuration:1 andParentView:self.collectionView];
                //[self.courseItemArray removeObjectAtIndex:pos];
                //[self.tableView reloadData];
                //                if(pos!=0){
                //                    NSIndexPath *curIndexPath=[NSIndexPath indexPathForRow:pos-1 inSection:0];
                //
                //                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:curIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                //                    [self.tableView scrollToRowAtIndexPath:curIndexPath atScrollPosition:pos-1 animated:YES];
                //                }
                [self loadingCourseFunction:self.currentSelectTime];
            }else{
                NSString *message =responseData[@"message"];
                WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
                [alertView showXLAlertView];
            }
            
        } failure:^(NSError *error, NSInteger errCode) {
            //DLog(@"加载 失败  %@ ",error.debugDescription);
            [weakSelf stopLoading];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"取消组队验证失败" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }];
    };
    [alertView showXLAlertView];
    
    
}


-(void) coureItemClickFunction:(SINAStuHomeCoursItemModel*)model andWithFlagIndex:(NSInteger)index{
    if (index==1) {
        //签到
        //        if ([self checkCoureSignFunction:model]) {
        //            if (model.tstatus!=nil&&[model.tstatus integerValue]==1001) {
        //                [YPXToastView showToastViewWithText:@"已签到" andDuration:1 andParentView:self.mainContentView];
        //            }else{
        //                [self coureSignFunction:model:0];
        //            }
        //        }
        DLog(@"点击签到 %@",model.tstatus);
        if (model.tstatus!=nil&&[model.tstatus integerValue]==1001) {
            [YPXToastView showToastViewWithText:@"已签到" andDuration:1 andParentView:self.mainContentView];
        }else{
            if ([self checkCoureSignFunction:model]) {
                [self coureSignFunction:model:0];
            }
        }
    }
}
//校验签到
-(BOOL) checkCoureSignFunction:(SINAStuHomeCoursItemModel*)model{
    
    //当前时间
    NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
    DLog(@"课程签到当前时间是 %ld",(long)currentTime);
    
    //课程开始时间
    NSInteger courseStartTime = [model.courseStartTime integerValue];
    DLog(@"课程签到当前时间是 courseStartTime %ld",(long)courseStartTime);
    //课程结束时间
    NSInteger courseEndTime = [model.courseEndTime integerValue];
    
    //开课前50分钟可签到
    NSInteger signStartTime = courseStartTime -1000*courseSignPreTime*60;
    NSInteger signEndTime = courseStartTime +1000*courseSignPreTime*60;
    DLog(@"课程签到当前时间是 signStartTime  %ld",(long)signStartTime);
 
    if (currentTime<signStartTime) {
        [YPXToastView showToastViewWithText:@"未到上课时间" andDuration:3 andParentView:self.mainContentView];
        return NO;
    }else if (currentTime>signStartTime&&currentTime<signEndTime){
        DLog(@"可签到");
        
        //校验地址
        NSString *courseLat = model.courseLocationLat;
        NSString *courseLng = model.courseLocationLon;
        
        
        if (courseLat==nil||courseLng==nil) {
            [YPXToastView showToastViewWithText:@"不在教室签到范围中" andDuration:3 andParentView:self.mainContentView];
            return NO;
        }else{
            NSString *currentTime =[SINACalendarUtils currentTimeStr];
            NSInteger flagUpdateLocationTime=0;
            if (self.preUpdateLocationTime==nil) {
                flagUpdateLocationTime=0;
            } else {
                flagUpdateLocationTime = [currentTime integerValue]-[self.preUpdateLocationTime integerValue];
            }
            if (flagUpdateLocationTime<0) {
                flagUpdateLocationTime=0;
            }
            if (self.locationLat==nil||flagUpdateLocationTime>courseSignUpdate*60*1000) {
                //重新获取坐标
                [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
                   
                    if (error)
                    {
                        DLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                        [YPXToastView showToastViewWithText:@"位置刷新失败" andDuration:3 andParentView:self.mainContentView];
                        if (error.code == AMapLocationErrorLocateFailed)
                        {
                            return;
                        }
                    }
                    
                    DLog(@"location:%@", location);
                    
                    if (regeocode)
                    {
                        DLog(@"reGeocode:%@", regeocode);
                        self.preUpdateLocationTime =[SINACalendarUtils currentTimeStr];
                        
                        self.locationLat=[NSString stringWithFormat:@"%f",location.coordinate.latitude];
                        self.locationLng=[NSString stringWithFormat:@"%f",location.coordinate.longitude];
                        
                        //校验距离
                        double flagDistance = [self distanceBetweenOrderBy:[courseLat doubleValue]  :[self.locationLat doubleValue] :[courseLng doubleValue]:[self.locationLng doubleValue] ];
                        
                        if (flagDistance<=courseSignDistance) {
                            //可签到
                            [YPXToastView showToastViewWithText:@"位置刷新成功 请重新签到" andDuration:3 andParentView:self.mainContentView];
                        } else {
                            self.locationLat=nil;
                            //不可签到
                            [YPXToastView showToastViewWithText:@"不在教室签到范围中" andDuration:3 andParentView:self.mainContentView];
                            
                        }
                        
                    }
                }];
            } else {
                //校验距离
                double flagDistance = [self distanceBetweenOrderBy:[courseLat doubleValue]  :[self.locationLat doubleValue] :[courseLng doubleValue]:[self.locationLng doubleValue] ];
                
                if (flagDistance<=courseSignDistance) {
                    //可签到
                    return YES;
                } else {
                    self.locationLat=nil;
                    //不可签到
                    [YPXToastView showToastViewWithText:@"不在教室签到范围中" andDuration:3 andParentView:self.mainContentView];
                    return NO;
                }
                
            }
        }
        
        
        return YES;
    }else if (currentTime>signEndTime&&currentTime<courseEndTime){
        DLog(@"老师发起点名可签到");
        if (model.tecSignStartTime==nil) {
            [YPXToastView showToastViewWithText:@"已经开始上课了 暂不可签到" andDuration:3 andParentView:self.mainContentView];
            return NO;
        } else {
            return YES;
        }
        
    }else {
        
        [YPXToastView showToastViewWithText:@"课程已结束" andDuration:3 andParentView:self.mainContentView];
        return NO;
        
        //        if (model.tecSignStartTime==nil) {
        //            [YPXToastView showToastViewWithText:@"课程已结束" andDuration:3 andParentView:self.mainContentView];
        //            return NO;
        //        } else {
        //            return YES;
        //        }
    }
    
}

-(double )distanceBetweenOrderBy:(double) lat1 :(double) lat2 :(double) lng1 :(double) lng2{
    
    CGFloat xDist = (lat1 - lat2);
    
    CGFloat yDist = (lng1- lng2);
    
    CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist));
    
    DLog("距离 %f",distance);
    return  distance;
}

-(void) coureSignFunction:(SINAStuHomeCoursItemModel*) model:(NSInteger)flag{
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    if (model.courseSyUid==nil&&model.courseId==nil) {
        [YPXToastView showToastViewWithText:@"课程数据异常 请刷新" andDuration:3 andParentView:self.mainContentView];
        return;
    }
    
    
    if (flag==0) {
        //课程表uuid String syllabusuuid
        [dict setObject:model.courseSyUid forKey:@"syllabusuuid"];
        //每周上课的课程信息uuid String syllabusacuuid
        if (model.courseUid==nil) {
            [YPXToastView showToastViewWithText:@"课程数据异常 请刷新" andDuration:3 andParentView:self.mainContentView];
            return;
        }
        [dict setObject:model.courseUid forKey:@"syllabusacuuid"];
    }else{
        [dict setObject:model.courseId forKey:@"syllabusac"];
        [dict setObject:model.courseSyId forKey:@"syllabusid"];
    }
    
    //经度 String lati
    //维度 String lon
    //海拔 String height
    //学生的uuid String studentuuid
    [dict setObject:[[SINACommonUserHelper share]getUserModel].userUid forKey:@"studentuuid"];
    
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    [self startLoading];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,stuCourseSignUrl] withParamters:dict2 success:^(id responseData) {
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            [YPXToastView showToastViewWithText:@"签到成功" andDuration:3 andParentView:self.collectionView];
            [weakSelf loadingCourseFunction:self.currentSelectTime];
            
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败");
        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"签到验证失败" sureBtn:@"确定" cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}

-(void)showHomeTimeSelect{
    [self selectTime];
}


//选择时间
-(void) selectTime{
    
    
    SINACommonTimePickView *timePickView =[[SINACommonTimePickView alloc]init];
    
    timePickView.titleLabel.text=@"选择时间";
    
    [timePickView comTimePicViewDefaultSelect:timePickView andWithYear:self.currentYear andWithMonth:self.currentMonth andWithDay:self.currentDay andWithHoure:8 andWithMin:0 andWithSec:0];
    
    timePickView.delegate=self;
    timePickView.currentTimeStyle=YEAER_MAONTH_DAY;
    [timePickView show];
}

-(void)pickerDateView:(SINAPickDateView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day selectHours:(NSInteger)hour{
    
}

-(void)pickerDateView:(SINAPickDateView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day selectHours:(NSInteger)hour selectMins:(NSInteger)min selectSecond:(NSInteger)second{
    
    
}

#pragma - CommonTimeSelectViewDelegate Method
- (void)dismissServiceTimeSelectPickView:(SINACommonTimePickView *)customPickView
{
    
}


-(void)commonTimeSelectPickView:(SINACommonTimePickView *)customPickView andWithYear:(NSString *)year andWithMonth:(NSString *)month andWithDay:(NSString *)day andWithHoure:(NSString *)hour andWithMin:(NSString *)min andWithSec:(NSString *)sec{
    DLog(@" home time select %@年%@月%@日 %@时%@分%@秒",year,month,day,hour,min,sec);
    
    
    BOOL isRoatFlag = NO;
    if (self.currentYear!=[year integerValue]||self.currentMonth!=[month integerValue]) {
        isRoatFlag=YES;
    }
    
    self.currentYear =[year integerValue];
    self.currentMonth = [month integerValue];
    self.currentDay = [day integerValue];
    
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd";
    NSString * dateString1 =[NSString stringWithFormat:@"%ld-%ld-%ld",self.currentYear,self.currentMonth,self.currentDay];
    NSDate * date = [df dateFromString:dateString1];
    
    self.currentSelectTime =[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]];
    
    if (isRoatFlag) {
        CABasicAnimation* rotationAnimation;
        //绕哪个轴，那么就改成什么：这里是绕y轴 ---> transform.rotation.y
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
        //旋转角度
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI];
        //每次旋转的时间（单位秒）
        rotationAnimation.duration = 0.4;
        rotationAnimation.cumulative = YES;
        //重复旋转的次数，如果你想要无数次，那么设置成MAXFLOAT
        rotationAnimation.repeatCount = 0;
        [self.headerLabel.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    }
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (400*USEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.headerLabel.text =[NSString stringWithFormat:@" %ld·%ld月",(long)self.currentYear,self.currentMonth];
    });
    //初始化时间数据
    [self initTimeFunction:1];
    //更新日期显示
    [self.collectionView reloadData];
    [self.collectionView setContentOffset:CGPointMake((self.currentPos-3)*self.dateItemWidth, self.collectionView.contentOffset.y) animated:YES];
    //刷新首页面数据
    [self loadingCourseFunction:self.currentSelectTime];
}

#pragma mark - BasePickViewDelegate method
- (void)dismissBasePickView:(SINABasePickView *)customPickView
{
    
}





@end
